/**
 * 统计数据相关状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  getDashboardStats,
  getMostFavoriteItems,
  getMapPasswords,
  getPriceChangeItemsList
} from '@/api/stats'
import type {
  DashboardStats,
  PriceChangeItem,
  MapPassword,
  BulletTrend,
  HafcoinTrend,
  PriceIncreaseItem,
  PriceDecreaseItem
} from '@/api/types/stats'

export const useStatsStore = defineStore('stats', () => {
  // 状态
  const dashboardStats = ref<DashboardStats | null>(null)
  const favoriteItems = ref<PriceChangeItem[]>([])
  const priceIncreaseItems = ref<PriceIncreaseItem[]>([])
  const priceDecreaseItems = ref<PriceDecreaseItem[]>([])
  const mapPasswords = ref<MapPassword | null>(null)
  const bulletTrend = ref<BulletTrend | null>(null)
  const hafcoinTrend = ref<HafcoinTrend | null>(null)
  
  const loading = ref({
    dashboard: false,
    favorites: false,
    priceChanges: false,
    mapPasswords: false,
    bulletTrend: false,
    hafcoinTrend: false
  })

  // 错误状态
  const errors = ref({
    dashboard: null as Error | null,
    favorites: null as Error | null,
    mapPasswords: null as Error | null
  })

  // 计算属性
  const hasStats = computed(() => dashboardStats.value !== null)
  const hasTrendData = computed(() => bulletTrend.value !== null && hafcoinTrend.value !== null)

  // 方法
  const fetchDashboardStats = async () => {
    loading.value.dashboard = true
    errors.value.dashboard = null

    try {
      const response = await getDashboardStats()
      if (response && response.code === 1 && response.data) {
        dashboardStats.value = response.data
      } else {
        console.warn('获取首页统计数据返回异常状态码:', response?.code, response?.message)
        throw new Error(`API错误: ${response?.message || '未知错误'}`)
      }
    } catch (error) {
      console.error('获取首页统计数据失败:', error)
      errors.value.dashboard = error as Error
      dashboardStats.value = null
    } finally {
      loading.value.dashboard = false
    }
  }

  const fetchFavoriteItems = async (limit: number = 10) => {
    loading.value.favorites = true
    errors.value.favorites = null

    try {
      const response = await getMostFavoriteItems(limit)
      if (response && response.code === 1 && response.data && response.data.top_favorite_items) {
        // 将top_favorite_items转换为PriceChangeItem格式，保留favorite_count和grade
        favoriteItems.value = response.data.top_favorite_items.map(item => ({
          id: item.id,
          object_id: item.id,
          name: item.name,
          image_url: item.image_url,
          favorite_count: item.favorite_count,
          grade: item.grade,
          current_price: 0,
          previous_price: 0,
          change_value: 0,
          change_percentage: 0,
          trend: 'stable' as const
        }))
      } else {
        console.warn('获取热门物品返回异常状态码:', response?.code, response?.message)
        throw new Error(`API错误: ${response?.message || '未知错误'}`)
      }
    } catch (error) {
      console.error('获取热门物品失败:', error)
      errors.value.favorites = error as Error
      favoriteItems.value = []
    } finally {
      loading.value.favorites = false
    }
  }

  const fetchPriceChangeItems = async (limit: number = 10) => {
    loading.value.priceChanges = true
    try {
      const response = await getPriceChangeItemsList()
      if (response && response.code === 1 && response.data) {
        priceIncreaseItems.value = response.data.increase_items || []
        priceDecreaseItems.value = response.data.decrease_items || []
      } else {
        console.warn('获取价格变动物品返回异常状态码:', response?.code, response?.message)
        priceIncreaseItems.value = []
        priceDecreaseItems.value = []
      }
    } catch (error) {
      console.error('获取价格变动物品失败:', error)
      priceIncreaseItems.value = []
      priceDecreaseItems.value = []
    } finally {
      loading.value.priceChanges = false
    }
  }

  const fetchMapPasswords = async () => {
    loading.value.mapPasswords = true
    errors.value.mapPasswords = null

    try {
      const response = await getMapPasswords()
      if (response && response.code === 1 && response.data) {
        mapPasswords.value = response.data
      } else {
        console.warn('获取地图密码返回异常状态码:', response?.code, response?.message)
        throw new Error(`API错误: ${response?.message || '未知错误'}`)
      }
    } catch (error) {
      console.error('获取地图密码失败:', error)
      errors.value.mapPasswords = error as Error
      mapPasswords.value = null
    } finally {
      loading.value.mapPasswords = false
    }
  }

  const fetchAllStats = async () => {
    const promises = [
      fetchDashboardStats().catch(err => console.error('获取仪表盘数据失败:', err)),
      fetchFavoriteItems().catch(err => console.error('获取热门物品失败:', err)),
      fetchPriceChangeItems().catch(err => console.error('获取价格变动失败:', err)),
      fetchMapPasswords().catch(err => console.error('获取地图密码失败:', err))
    ]
    
    await Promise.allSettled(promises)
  }

  const refreshStats = async () => {
    await fetchAllStats()
  }

  return {
    // 状态
    dashboardStats,
    favoriteItems,
    priceIncreaseItems,
    priceDecreaseItems,
    mapPasswords,
    bulletTrend,
    hafcoinTrend,
    loading,
    errors,
    
    // 计算属性
    hasStats,
    hasTrendData,
    
    // 方法
    fetchDashboardStats,
    fetchFavoriteItems,
    fetchPriceChangeItems,
    fetchMapPasswords,
    fetchAllStats,
    refreshStats
  }
})
